package com.web.imp;

import org.testng.annotations.AfterClass;
import org.testng.annotations.BeforeClass;

import com.app.AppContext;
import com.web.listeners.imp.UserPopulator;
import com.web.model.BrowserFactory;
import com.web.model.PageBrowser;
import com.web.model.WebBrowser;
import com.zyncro.user.ZyncroUserFactory;

public abstract class AbstractWebTest {

	private static final BrowserFactory browserFactory = AppContext.getBean(BrowserFactory.class);
	
	private static final UserPopulator userPopulator;

	static{
		
		ZyncroUserFactory userFactory = AppContext.getBean(ZyncroUserFactory.class);
		userPopulator = new UserPopulator(userFactory);
	}
	
	@BeforeClass
	public void beforeClass(){
		
		userPopulator.populateClass(this.getClass());
	}
	
	private PageBrowser browser;
	
	protected WebBrowser newBrowser(){
		
		this.browser = browserFactory.newBrowser();
		return browser;
	}
	
	protected WebBrowser getBrowser(){
		if (browser == null || !browser.isAlive()){
			this.browser = browserFactory.newBrowser();
		}
		return browser;
	}
	
	@AfterClass
	public void afterClass(){
		
		if (isThereBrowser()){
			browser.quit();
		}
	}
	
	public boolean isThereBrowser(){
		return browser != null && browser.isAlive();
	}
	
	public WebBrowser getTestBrowser(){
		
		if (isThereBrowser()){
			
			return browser;
		}
		else
			throw new IllegalStateException("There is no browser");
	}
}
